package com.cans.security.browser.handler;

import com.cans.security.properties.LoginResponseType;
import com.cans.security.properties.CansSecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author cans
 * @date 2017/11/14
 * @description security 认证失败处理
 */
@Component("cansAuthenticationFailureHandler")
public class CansAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private CansSecurityProperties cansSecurityProperties;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        logger.info("认证失败!");

        // 配置认证方式为JSON则返回json字符串
        if(LoginResponseType.JSON.equals(cansSecurityProperties.getBrowser().getLoginResponse())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
        }

        super.onAuthenticationFailure(request, response, exception);
    }
}
